package com.cet.juc;

import java.util.LinkedList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author: wod.Y
 * @date: 2022/4/25 17:36
 */
public class FutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        LinkedList<CompletableFuture<String>> futures = new LinkedList<>();
        //定义三个异步任务
        futures.add(CompletableFuture.supplyAsync(FutureDemo::getString1));
        futures.add(CompletableFuture.supplyAsync(FutureDemo::getString2));
        futures.add(CompletableFuture.supplyAsync(FutureDemo::getString3));
        //让任务开始运行
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
        //收集结果
        String result = "";
        for (CompletableFuture future : futures) result += future.join() + " ";
        long spend = System.currentTimeMillis() - start;
        System.out.println("spend:[" + spend + "ms],result:" + result);
    }

    static String getString1() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hello";
    }

    static String getString2() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "future";
    }

    static String getString3() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "shit";
    }
}

